/* eslint-disable no-undef */
let ws = "";
// if (!ws) {
//     ws = new WebSocket(url, 'usbkey-protocol')
// }

const state = {
  code: "",
  pinCode: "",
};
const mutations = {
  setRandonCode(state, data) {
    state.code = data.code;
  },
  setPinCode(state, data) {
    state.pinCode = data.code;
  },
};
const actions = {
  async getRandomCode({ commit }, callback) {
    try {
      // 获取签名使用的随机数
      const data = await axios.post(userServer.getRandomCode);
      commit("ukey/setRandonCode", {
        code: data,
      });
      callback({
        succ_status: 3,
        msg: "获取签名随机数成功",
        data: {
          random_code_status: true,
          random_code: data,
        },
      });
    } catch (err) {
      if (err && err.code) {
        callback({
          err_status: 6,
          msg: "获取签名随机数失败",
          data: {
            random_code_status: false,
            random_code: "",
          },
        });
      }
    }
  },
  async listenUkey(
    { dispatch, commit, state },
    request = { type: 0, pin_code: "", callback: () => {} }
  ) {
    try {
      var Path = ""; // 路径
      var insert_status = 0; // ukey的拔插事件会执行两次，防止第二次执行
      if (request.type != 0) {
        // 不是初始化流程
        let socketStatus = ws.GetWebsocketStatus();
        if (socketStatus == 0) {
          setTimeout(() => {
            ws.send(JSON.stringify({ FunName: "ResetOrder" }));
          }, 500);
        } else {
          ws.send(JSON.stringify({ FunName: "ResetOrder" }));
        }
      }
      ws.Socket_UK.onopen = function() {
        ws.send(JSON.stringify({ FunName: "ResetOrder" })); // 这里调用ResetOrder将计数清零，这样，消息处理处就会收到0序号的消息，通过计数及序号的方式，从而生产流程
      };

      // 在使用事件插拨时，注意，一定不要关掉Sockey，否则无法监测事件插拨
      ws.onmessage = function(Msg) {
        let PnpData = JSON.parse(Msg.data);
        if (PnpData.type == "PnpEvent") {
          // 如果是插拨事件处理消息
          if (PnpData.IsIn) {
            // 监听到插入
            if (insert_status === 1) return;
            console.log("ukey插入");
            insert_status = 1;
            ws.send(JSON.stringify({ FunName: "ResetOrder" }));
          } else {
            // 监听到拔出
            if (insert_status === 2) return;
            console.log("ukey拔出");
            insert_status = 2;
            if (typeof request.callback == "function") {
              request.callback({
                err_status: 2,
                msg: NO_UKEY,
              });
            }
            if (route.history.current.path == "/") return false;
            // 检测到UKEY拔出，退出登录
            return;
          }
        }

        if (PnpData.type == "Process") {
          // 如果是事件处理流程
          var order = PnpData.order;
          if (state.serve_random_code.length == 0) {
            dispatch("ukey/getRandomCode", {
              commit,
              callback: request.callback,
            });
          } else {
            if (typeof request.callback == "function") {
              request.callback({
                succ_status: 3,
                msg: "获取签名随机数成功",
                data: {
                  random_code_status: true,
                  random_code: state.serve_random_code,
                },
              });
            }
          }
          if (order == 0) {
            ws.send(JSON.stringify({ FunName: "FindPort", start: start })); // 查找加密锁
          } else if (order == 1) {
            if (PnpData.LastError != 0) {
              if (typeof request.callback == "function") {
                request.callback({
                  err_status: 2,
                  msg: "未检测到UKEY",
                });
              }
              return false;
            }
            // 已插入UKEY
            Path = PnpData.return_value; // 获得返回的UK的路径
            ws.send(JSON.stringify({ FunName: "GetChipID", Path: Path })); // 获取锁唯一ID
          } else if (order == 2) {
            // 获取到锁ID
            if (PnpData.LastError != 0) {
              if (typeof request.callback == "function") {
                request.callback({
                  err_status: 3,
                  msg: "获取锁ID失败",
                });
              }
              return false;
            }

            if (typeof request.callback == "function") {
              request.callback({
                succ_status: 1,
                msg: "获取锁ID成功。",
                data: {
                  ukey_id: PnpData.return_value,
                },
              });
            }
            // 返回设置在锁中的用户名
            ws.send(JSON.stringify({ FunName: "GetSm2UserName", Path: Path }));
          } else if (order == 3) {
            // 获取到用户身份
            if (PnpData.LastError != 0) {
              if (typeof request.callback == "function") {
                request.callback({
                  err_status: 4,
                  msg: "获取用户名失败。",
                });
              }

              request.callback({
                err_status: 4,
                msg: "获取用户名失败。",
              });
              return false;
            }
            if (typeof request.callback == "function") {
              request.callback({
                succ_status: 2,
                msg: "获取用户身份成功。",
                data: {
                  account: PnpData.return_value,
                },
              });
            }
          }

          if (request.type == 1) {
            // 验证Pin码
            if (order == 3) {
              // 对数据进行签名，验证pin码，在内部会验证pin码，验证正确后才能够签名，验证错误后则pin码错误
              ws.send(
                JSON.stringify({
                  FunName: "YtSign",
                  SignMsg: state.SignMsg,
                  Pin: state.Pin,
                  Path: Path,
                })
              );
            } else if (order == 4) {
              if (PnpData.LastError != 0) {
                request.callback({
                  err_status: 5,
                  msg: "Pin码验证失败。",
                });
                return false;
              }
              request.callback({
                succ_status: 4,
                msg: "签名成功",
                data: {
                  autograph: PnpData.return_value,
                },
              });
              commit("ukey/setPinCode", {
                code: request.pin_code,
              });
            }
          }
        }
      };

      ws.onerror = function() {
        console.log("连接错误");
      };
      ws.onclose = function() {
        console.log("连接关闭");
      };
    } catch (e) {
      console.error(e.name + ": " + e.message);
      return false;
    }
  },
};
export default {
  namespaced: true,
  state,
  actions,
  mutations,
};
